package com.codecrane.core.power.controller;

import com.codecrane.core.web.Ajax;
import com.codecrane.core.web.AjaxReturn;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.*;
import java.lang.management.ManagementFactory;

/**
 * 数据管理更新模块
 * Created by crane on 17/3/20.
 */
@Controller
@RequestMapping("/power/dbmanager")
public class DbManagerController {

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    /**
     * 数据管理页面
     *
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/main", method = RequestMethod.GET)
    public String manager(ModelMap modelMap) {

        return "/power/dbmanager/main";
    }


    /**
     * SQL执行
     *
     * @param sql
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/run", method = RequestMethod.POST)
    public AjaxReturn runScript(@RequestParam("sql") String sql) {
        AjaxReturn webResult = Ajax.fail().setMsg("执行失败!");
        if (null != sqlSessionFactory) {
            ScriptRunner scriptRunner = new ScriptRunner(sqlSessionFactory.openSession().getConnection());
            scriptRunner.setAutoCommit(false);
            scriptRunner.setSendFullScript(true);
            scriptRunner.setThrowWarning(true);
            scriptRunner.setStopOnError(true);
            if (StringUtils.isNotBlank(sql)) {
                //TODO 非法sql过滤
                sql = StringUtils.trim(sql);
                Reader reader = new StringReader(sql);
                try {
                    File logFile = new File("sqldebug.log");
                    PrintWriter pw = new PrintWriter(logFile);
                    scriptRunner.setLogWriter(pw);
                    scriptRunner.runScript(reader);
                    webResult.setOk(true).setMsg("执行完毕!").setData(FileUtils.readFileToString(logFile,"utf-8"));
                } catch (Exception e) {
                    e.printStackTrace();
                    webResult.setMsg("执行异常!");
                }
            } else {
                webResult.setMsg("执行的SQL不能为空!");
            }
        }
        return webResult;
    }

}
